/*
 *    Copyright(c)2023-2024
 *    项目名称:hello-world
 *    文件名称:AsyncConfig.java
 *    Date:2023/11/19 下午7:03
 *    Author:赵士杰
 */

package com.hw.framework.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @Project：hello-world
 * @ClassName AsyncConfig
 * @Description 异步任务配置
 * @Author 赵士杰
 * @Date 2023/10/28 21:02
 */
@Configuration
public class AsyncConfig implements AsyncConfigurer {

    // 核心线程池大小
    private int corePoolSize = 50;

    // 最大可创建的线程数
    private int maxPoolSize = 200;

    // 队列最大长度
    private int queueCapacity = 1000;

    // 线程池维护线程所允许的空闲时间
    private int keepAliveSeconds = 300;

    private String threadNamePrefix = "Async-Task-";

    /**
     * 获取异步执行任务的线程池对象
     * @return 线程池对象
     */
    @Bean
    @Override
    public Executor getAsyncExecutor() {
        // 创建 ThreadPoolTaskExecutor 对象
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 设置最大线程数
        executor.setMaxPoolSize(maxPoolSize);
        // 设置核心线程数
        executor.setCorePoolSize(corePoolSize);
        // 设置任务队列容量，用于缓存等待执行的任务
        executor.setQueueCapacity(queueCapacity);
        // 设置线程名称前缀，用于区分不同的线程
        executor.setThreadNamePrefix(threadNamePrefix);
        // 设置线程空闲时间，即当线程池中的线程空闲时间超过该值时，多余的线程会被回收
        executor.setKeepAliveSeconds(keepAliveSeconds);
        // 设置线程池对拒绝任务(无线程可用)的处理策略，这里使用 CallerRunsPolicy，即由调用线程执行任务
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 返回线程池对象
        return executor;
    }


}
